<?php
use yii\bootstrap\ActiveForm;
use common\helps\tools;
?>
<link rel="stylesheet" href="../static/dist/css/AdminLTE.min.css" type="text/css">
<link rel="stylesheet" href="../static/bootstrap/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="../static/plugins/datatables/jquery.dataTables.css" type="text/css">
<link rel="stylesheet" href="../static/css/admin.css" type="text/css">
<link rel="stylesheet" href="../static/jBox/Skins/Metro/jbox.css" type="text/css">
<style>
    .dataTable>tbody>tr>td{
        vertical-align: middle;
        font-size: 0.8em;
        padding: 8px 18px;
    }
    .dataTable>thead>tr>th{
        vertical-align: middle;
        font-size: 0.8em;
        text-align: center;
    }
    .examine-content .input-group .form-control{
        margin-bottom: 20px;
        height: 30px ;
        line-height: 30px;
    }
    .examine-content button{
        margin: 10px;
    }
    label{
        text-align: right;
    }
    #table_id_example th, td {
        white-space: nowrap;
    }
    #table_list th,td{ font-family: '微软雅黑'; font-size: small; text-align: center}

</style>
<div class="tabs-panel">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-body">
                    <div class="col-md-12">
                        仓库：<select id="warehouseId" name="warehouseId" class="depart-input" style="width: 200px">
                                <option value="">选择仓库</option>
                                <?php foreach($warehouse as $value) { ?>
                                    <option value="<?= $value['id']?>" <?=($stock&&$stock['warehouseId']==$value['id'])?'selected':'' ?>><?= $value['warehouseName']?></option>
                                <?php }?>
                            </select>&nbsp;&nbsp;
                            <button type="button" class="btn btn-default" id="wh-confirm-btn" style="width:70px; margin-bottom: 5px">确认</button>&nbsp;&nbsp;
                            <button type="button" class="btn btn-primary" id="show-materiel-btn" style="width: 100px; margin-bottom: 5px">查询</button>
                    </div>

                    <div class="col-md-12" style="margin-top: 30px">
                        <table id="table_list" class="table table-bordered table-hover">
                            <thead>
                            <tr>
                                <th style="width: 7%">物料ID</th>
                                <th style="width: 7%">物料名称</th>
                                <th style="width: 7%">所属仓库</th>
                                <th style="width: 8%">供应商</th>
                                <th style="width: 7%">批次</th>
                                <th style="width: 7%">单价</th>
                                <th style="width: 8%">生产日期</th>
                                <th style="width: 8%">到期日期</th>
                                <th style="width: 7%">总数量</th>
                                <th style="width: 7%">冻结数量</th>
                                <th style="width: 7%">可用数量</th>
                                <th style="width: 7%">盘亏/盘盈</th>
                                <th style="width: 7%">调整数量</th>
                                <th style="width: 6%">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if($stock && $stock['dtl']){ foreach ($stock['dtl'] as $dtl){ ?>
                                <tr data-code="<?= $dtl['stockId'] ?>">
                                    <td><?= $dtl['materielId'] ?></td>
                                    <td><?= $dtl['materielName'] ?></td>
                                    <td><?= $dtl['warehouseName'] ?></td>
                                    <td><?= $dtl['supplierName'] ?></td>
                                    <td><?= $dtl['batch'] ?></td>
                                    <td><?= $dtl['price'] ?></td>
                                    <td><?= $dtl['productDate'] ?></td>
                                    <td><?= $dtl['safeDate'] ?></td>
                                    <td><?= $dtl['total'] ?></td>
                                    <td><?= $dtl['freeze'] ?></td>
                                    <td><?= $dtl['qty'] ?></td>
                                    <td><?= $dtl['dType'] == '0' ? '盘盈' : '盘亏' ?></td>
                                    <td style="color: <?= $dtl['dType'] == '0' ? '#00a65a' : '#dd4b39' ?>;"><?= $dtl['editQty'] ?></td>
                                    <td><?php if($stock['stockStatus']=='0'){ ?><a name="del-materiel">删除</a><?php } ?></td>
                                </tr>
                            <?php } } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="box-footer" style="padding: 0 30px">
                    <div style="float: left">
                        备注：<br>
                        <textarea name="remark" id="remark" cols="50" rows="5"><?=$stock?$stock['remark']:''?></textarea>
                    </div>
                    <div style="float: right; padding-top: 88px">
                        <button type="button" class="btn btn-default" onclick="history.back();">返回</button>
                        <button type="button" class="btn btn-primary hideBtn" onclick="saveRevise()">提交</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="add-materiel-modal" style="background: rgba(236, 230, 230, 0.3);" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 90%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">添加物料</h4>
            </div>
            <div class="modal-body">
                <div class="box-header">
                    物料名称/编号: <input class="depart-input" id="searchKey" type="text">&nbsp;&nbsp;
                    批次: <input class="depart-input" id="searchBatch" type="text">
                    <button type="button" class="btn btn-primary depart-modal" id="search-btn" style="width: 100px;">查询</button> &nbsp;
                </div>
                <div class="box-body">
                    <table id="search_list" class="display">
                        <thead>
                        <tr>
                            <th style="width: 9%">物料ID</th>
                            <th style="width: 9%">物料名称</th>
                            <th style="width: 10%">所属仓库</th>
                            <th style="width: 9%">供应商</th>
                            <th style="width: 9%">批次</th>
                            <th style="width: 9%">单价</th>
                            <th style="width: 9%">总数</th>
                            <th style="width: 9%">冻结数</th>
                            <th style="width: 9%">可用数</th>
                            <th style="width: 9%">操作</th>
                            <th style="width: 10%">调整数量</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="add-materiel-btn">添加</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript" src="../static/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="../static/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../static/plugins/datatables/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="../static/plugins/datatables/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="../static/jBox/jquery.jBox-2.3.min.js"></script>
<script type="text/javascript" src="../static/jBox/i18n/jquery.jBox-zh-CN.js"></script>
<!-- 自定义js -->
<script type="text/javascript" src="/static/app/global.js?version=<?=Yii::$app->params['version']?>"></script>
<script type="text/javascript" src="../static/app/stock/index.js?version=<?=Yii::$app->params['version']?>"></script>

<script>
    var tempData = {};
    var selectData = {};
    var searchDataTable = null;
    var stockNo = '';
    var confirmFlg = 0, dateFlg = 0;

    <?php if($stock){ ?>
    stockNo = '<?=$stock['stockNo']?>';
    $('#warehouseId').attr('disabled','true').css('color', '#ccc');
    <?php if($stock['stockStatus']=='0'){ ?>
    <?php if($stock['dtl']){ foreach ($stock['dtl'] as $dtl){ ?>
    selectData[<?=$dtl['stockId']?>] = {
        stockId: '<?=$dtl['stockId']?>',
        materielId:'<?=$dtl['materielId']?>',
        materielName: '<?=$dtl['materielName']?>',
        warehouseName: '<?=$dtl['warehouseName']?>',
        supplierId: '<?=$dtl['supplierId']?>',
        supplierName: '<?=$dtl['supplierName']?>',
        batch: '<?=$dtl['batch']?>',
        price: '<?=$dtl['price']?>',
        total: '<?=$dtl['total']?>',
        freeze:'<?=$dtl['freeze']?>',
        qty:'<?=$dtl['qty']?>',
        dType: '<?=$dtl['dType']?>',
        amount: '<?=$dtl['editQty']?>',
        productDate: '<?=$dtl['productDate']?>',
        safeDate: '<?=$dtl['safeDate']?>',
    };

    confirmFlg = 1;
    $('#wh-confirm-btn').text('重置');
    <?php }}} else { ?>
    $('input,textarea').attr("disabled","disabled");
    $('#wh-confirm-btn').hide();
    $('#show-materiel-btn').hide();
    $('.hideBtn').hide();
    <?php }} ?>

    //确认、重置仓库
    $("#wh-confirm-btn").on('click', function () {
        if($(this).text()=='确认'){
            confirmFlg = 1;
            if($('#warehouseId').val()==''){
                $.jBox.tip('请选择仓库');
                return;
            }
            $('#warehouseId').attr('disabled','true').css('color', '#ccc');
            $(this).text('重置');
        }else{
            dateFlg = 1;
            confirmFlg = 0;
            selectData = {};
            tempData = {};
            $('#table_list tbody').html('');
            $('#warehouseId').removeAttr('disabled').css('color', '');
            $(this).text('确认');
        }
    });

    //初始化modal
    $('#show-materiel-btn').on('click', function () {
        if(!confirmFlg){
            $.jBox.tip('请确认仓库');
            return;
        }
        $('#add-materiel-modal').modal('show');
        if(searchDataTable){
            if(dateFlg){
                searchDataTable.ajax.reload();
                dateFlg= 0;
            }
            return;
        }

        searchDataTable = $('#search_list').DataTable({
            dom: '<"top">rt<"bottom"flip><"clear">',
            language: {
                "sUrl":'../static/plugins/datatables/language.json'
            },
            "searching": false,
            "processing": true,
            "serverSide": true,
            "ordering": false,
            ajax:{
                url:'/stock/get-materiel-stock',
                type:'post',
                data:function(d){
                    d.warehouseId = $('#warehouseId').val();
                    d.searchKey = $('#searchKey').val();
                    d.searchBatch = $('#searchBatch').val();
                },
                error:getError
            },
            aoColumns: [
                { "data": "materielId"},
                { "data": "materielName"},
                { "data": "warehouseName"},
                { "data": "supplierName"},
                { "data": "batch"},
                { "data": "price"},
                { "data": "total"},
                { "data": "freeze"},
                { "data": "qty"},
                { "data": "materielId"},
                { "data": "materielId"}
            ],
            columnDefs: [
                {
                    "targets": [-1],
                    "orderable":false,
                    "searchable":false,
                    "render": function(data, type, full) {
                        var html = '', editQty = '';
                        if (selectData[data]) editQty = selectData[data]['editQty'];
                        html += '<input name="editQty" style="width: 50px" value="' + editQty + '">';
                        html += '<input type="hidden" name="id" value="' + full.id + '">';
                        html += '<input type="hidden" name="productDate" value="' + full.productDate + '">';
                        html += '<input type="hidden" name="safeDate" value="' + full.safeDate + '">';
                        html += '<input type="hidden" name="supplierId" value="' + full.supplierId + '">';
                        return html;
                    }
                },
                {
                    "targets": [-2],
                    "orderable": false,
                    "searchable": false,
                    "render": function (data, type, full) {
                        var dType = '';
                        if (selectData[data]) dType = selectData[data]['dType'];
                        var html = '<select name="dType" style="width: 60px">';
                        html += '<option value="0" style="color: #00a65a" ' + (dType=='0' ? 'selected' : '') + '>盘盈</option>';
                        html += '<option value="1" style="color: #dd4b39" ' + (dType=='1' ? 'selected' : '') + '>盘亏</option>';
                        html += '</select>';
                        return html;
                    }
                }
            ]
        });
    });

    //modal 搜索按钮
    $('#search-btn').on('click', function () {
        if(searchDataTable) {
            searchDataTable.ajax.reload();
            return;
        }
    });

    //modal 选中/取消 checkbox
    $('#search_list').on('blur', 'input[name=editQty]', function () {
        var _tr = $(this).parents('tr');
        addTempData(_tr);
    });
    $('#search_list').on('change', 'select', function () {
        var _tr = $(this).parents('tr');
        addTempData(_tr);
    });
    function addTempData(_tr) {

        var code = _tr.find('input[name=id]').val();
        var editQty = _tr.find('input[name=editQty]').val();
        if(!editQty){
            if (tempData[code]) {
                delete tempData[code];
            }
            return;
        }

        if (tempData[code]) {
            tempData[code]['total'] = _tr.find('td').eq(6).html();
            tempData[code]['freeze'] = _tr.find('td').eq(7).html();
            tempData[code]['qty'] = _tr.find('td').eq(8).html();
            tempData[code]['dType'] = _tr.find('select[name=dType]').val();
            tempData[code]['amount'] = editQty;
        } else {
            tempData[code] = {
                stockId: code,
                materielId: _tr.find('td').eq(0).html(),
                materielName: _tr.find('td').eq(1).html(),
                warehouseName: _tr.find('td').eq(2).html(),
                supplierName: _tr.find('td').eq(3).html(),
                batch: _tr.find('td').eq(4).html(),
                price: _tr.find('td').eq(5).html(),
                total: _tr.find('td').eq(6).html(),
                freeze: _tr.find('td').eq(7).html(),
                qty: _tr.find('td').eq(8).html(),
                dType: _tr.find('select[name=dType]').val(),
                amount: editQty,
                productDate: _tr.find('input[name=productDate]').val(),
                safeDate: _tr.find('input[name=safeDate]').val(),
                supplierId:  _tr.find('input[name=supplierId]').val(),
            };
        }
    }

    //modal 添加按钮
    $('#add-materiel-btn').on('click',function () {
        var html = '';
        $.each(tempData, function (i, v) {
            var str = v['dType'] == '0' ? '盘盈' : '盘亏';
            var color = v['dType'] == '0' ? '#00a65a' : '#dd4b39';
            if (selectData[i]) {
                delete selectData[i];
                $("#table_list").find('tr[data-code="' + i + '"]').remove();
            }
            if (v['editQty'] != '0' && v['editQty'] != '') {
                html += '<tr data-code="' + i + '">';
                html += '   <td>' + v['materielId'] + '</td>';
                html += '   <td>' + v['materielName'] + '</td>';
                html += '   <td>' + v['warehouseName'] + '</td>';
                html += '   <td>' + v['supplierName'] + '</td>';
                html += '   <td>' + v['batch'] + '</td>';
                html += '   <td>' + v['productDate'] + '</td>';
                html += '   <td>' + v['safeDate'] + '</td>';
                html += '   <td>' + v['price'] + '</td>';
                html += '   <td>' + v['total'] + '</td>';
                html += '   <td>' + v['freeze'] + '</td>';
                html += '   <td>' + v['qty'] + '</td>';
                html += '   <td>' + str + '</td>';
                html += '   <td style="color: ' + color + '">' + v['amount'] + '</td>';
                html += '   <td><a name="del-materiel">删除</a></td>';
                html += '</tr>';
                selectData[i] = v;
            }
        });
        dateFlg = 1;
        tempData = {}; //清空临时数据
        $('#table_list tbody').append(html);
        $('#add-materiel-modal').modal('hide');
    });

    //删除事件
    $(document).on('click','a[name=del-materiel]',function () {
        var _tr = $(this).parents('tr');
        delete selectData[_tr.attr('data-code')];
        _tr.remove();
    });

    //提交事件
    function saveRevise() {
        if($("#warehouseId").val()==''){
            $.jBox.tip('请选择仓库');
            return;
        }
        if($.isEmptyObject(selectData)){
            $.jBox.tip('请添加物料信息');
            return;
        }
        var errMsg = '';
        var trList = $("#table_list tbody").find('tr[data-code]');
        $.each(trList, function () {
            var code = $(this).attr('data-code');
            if($.isEmptyObject(selectData[code])) {
                errMsg = '数据异常，请刷新页面后重试';
                return false;
            }
        });

        if(errMsg){ $.jBox.tip(errMsg); return; }

        var stockData = {
            stockNo:stockNo,
            sType: '1',
            warehouseId: $("#warehouseId").val(),
            remark: $("#remark").val(),
            materiels:selectData
        }
        $.post('/stock/save-stock', stockData,
            function (data) {
                if(data.code == 200){
                    $.jBox.tip('保存成功', 'success');
                    window.setTimeout(function () {
                        history.back();
                    }, 1000);
                }else{
                    $.jBox.error(data.val, '错误');
                }
            },
            'json'
        );
    }

</script>